/**
 * 更新装备基础数据价格脚本
 * 根据标准数据的价格规律更新所有装备的价格
 */

const mysql = require('mysql2/promise');
require('dotenv').config({ path: './nestjs-app/.env' });

class EquipmentPriceUpdater {
  constructor() {
    this.connection = null;
  }

  async connect() {
    try {
      this.connection = await mysql.createConnection({
        host: process.env.DB_HOST || '43.143.253.188',
        port: process.env.DB_PORT || 3306,
        user: process.env.DB_USER || 'nextjs',
        password: process.env.DB_PASS || 'yEAiRE2jcxTyRBy5',
        database: process.env.DB_NAME || 'nextjs',
        timezone: '+08:00'
      });
      console.log('✅ 数据库连接成功');
    } catch (error) {
      console.error('❌ 数据库连接失败:', error.message);
      throw error;
    }
  }

  async disconnect() {
    if (this.connection) {
      await this.connection.end();
      console.log('🔌 数据库连接已关闭');
    }
  }

  /**
   * 计算装备价格
   * 价格公式: price = 1500 * Math.pow(2, level - 1)
   */
  calculatePrice(level) {
    return 1500 * Math.pow(2, level - 1);
  }

  /**
   * 更新所有装备的价格
   */
  async updateAllEquipmentPrices() {
    try {
      console.log('🔄 开始更新装备价格...');

      // 获取所有装备数据
      const [equipments] = await this.connection.execute(
        'SELECT id, level, name FROM equipment_base ORDER BY level, id'
      );

      console.log(`📊 找到 ${equipments.length} 个装备需要更新价格`);

      let updatedCount = 0;
      const priceStats = {};

      for (const equipment of equipments) {
        const newPrice = this.calculatePrice(equipment.level);
        
        // 更新价格
        await this.connection.execute(
          'UPDATE equipment_base SET price = ? WHERE id = ?',
          [newPrice.toString(), equipment.id]
        );

        // 统计价格分布
        if (!priceStats[equipment.level]) {
          priceStats[equipment.level] = 0;
        }
        priceStats[equipment.level]++;

        updatedCount++;
        
        if (updatedCount % 10 === 0) {
          console.log(`📝 已更新 ${updatedCount}/${equipments.length} 个装备`);
        }
      }

      console.log(`✅ 价格更新完成！共更新 ${updatedCount} 个装备`);

      // 显示价格统计
      console.log('\n📊 价格分布统计:');
      Object.keys(priceStats).sort((a, b) => parseInt(a) - parseInt(b)).forEach(level => {
        const price = this.calculatePrice(parseInt(level));
        const count = priceStats[level];
        console.log(`  等级 ${level}: ${price.toLocaleString()} 银币 (${count} 个装备)`);
      });

    } catch (error) {
      console.error('❌ 更新装备价格失败:', error.message);
      throw error;
    }
  }

  /**
   * 验证价格更新结果
   */
  async verifyPriceUpdate() {
    try {
      console.log('\n🔍 验证价格更新结果...');

      // 按等级分组查询价格
      const [results] = await this.connection.execute(`
        SELECT level, price, COUNT(*) as count
        FROM equipment_base 
        GROUP BY level, price 
        ORDER BY level, price
      `);

      console.log('📋 价格验证结果:');
      results.forEach(result => {
        const expectedPrice = this.calculatePrice(result.level);
        const isCorrect = parseInt(result.price) === expectedPrice;
        const status = isCorrect ? '✅' : '❌';
        console.log(`  ${status} 等级 ${result.level}: ${result.price} (期望: ${expectedPrice}) - ${result.count} 个装备`);
      });

      // 检查是否有价格为0的装备
      const [zeroPriceCount] = await this.connection.execute(
        'SELECT COUNT(*) as count FROM equipment_base WHERE price = "0"'
      );

      if (zeroPriceCount[0].count > 0) {
        console.log(`⚠️  警告：仍有 ${zeroPriceCount[0].count} 个装备价格为0`);
      } else {
        console.log('✅ 所有装备价格都已正确更新');
      }

    } catch (error) {
      console.error('❌ 验证价格更新失败:', error.message);
      throw error;
    }
  }

  /**
   * 显示样本数据
   */
  async showSampleData() {
    try {
      console.log('\n📋 样本数据展示:');
      
      const [samples] = await this.connection.execute(`
        SELECT id, level, name, price 
        FROM equipment_base 
        ORDER BY level, id 
        LIMIT 20
      `);

      console.log('ID | 等级 | 名称 | 价格');
      console.log('---|------|------|------');
      samples.forEach(equipment => {
        console.log(`${equipment.id.toString().padStart(2)} | ${equipment.level.toString().padStart(2)} | ${equipment.name.padEnd(12)} | ${parseInt(equipment.price).toLocaleString()}`);
      });

    } catch (error) {
      console.error('❌ 显示样本数据失败:', error.message);
      throw error;
    }
  }

  /**
   * 运行完整的更新流程
   */
  async run() {
    try {
      await this.connect();
      await this.updateAllEquipmentPrices();
      await this.verifyPriceUpdate();
      await this.showSampleData();
      
      console.log('\n🎉 装备价格更新完成！');
      
    } catch (error) {
      console.error('💥 更新流程失败:', error.message);
      process.exit(1);
    } finally {
      await this.disconnect();
    }
  }
}

// 运行更新脚本
async function main() {
  const updater = new EquipmentPriceUpdater();
  await updater.run();
}

// 如果直接运行此脚本
if (require.main === module) {
  main().catch((error) => {
    console.error('💥 脚本执行失败:', error.message);
    process.exit(1);
  });
}

module.exports = EquipmentPriceUpdater;
